package com.huarui.part.dao.impl;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ewaf.framework.dao.impl.BaseDaoImpl;
import org.springframework.orm.ibatis.SqlMapClientCallback;

import com.huarui.part.dao.IPartUploadDao;
import com.huarui.part.model.PartUpload;
import com.ibatis.sqlmap.client.SqlMapExecutor;

public class PartUploadDao extends BaseDaoImpl implements IPartUploadDao {

	@Override
	public Integer getCountPartUploadByComId(Map<String, Object> map) {

		return (Integer) this.getSqlMapClientTemplate().queryForObject(
				namespace + ".getCountPartUploadByComId", map);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<PartUpload> getPartUploadListByComId(Map<String, Object> map) {

		return this.getSqlMapClientTemplate().queryForList(
				namespace + ".getPartUploadByComId", map);
	}

	@Override
	public PartUpload getPartUploadByCodeWithComapnyId(Integer companyId,
			String code) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", code);
		map.put("companyId", companyId);
		@SuppressWarnings("unchecked")
		List<PartUpload> list = getSqlMapClientTemplate().queryForList(
				namespace + ".getPartUpoadByCodeWithComId", map);

		if (list.size() == 0) {
			return null;
		} else {
			return list.get(0);
		}

	}

	@Override
	public int batchInsert(final List<PartUpload> list) {
		this.getSqlMapClientTemplate().execute(new SqlMapClientCallback() {
			public Object doInSqlMapClient(SqlMapExecutor executor)
					throws SQLException {
				executor.startBatch();
				int batch = 0;
				int total = 0;
				for (PartUpload item : list) {
					executor.insert(namespace + ".create", item);
					batch++;
					if (total % 500 == 0) {
						total += executor.executeBatch();
						batch = 0;
					}
				}
				total += executor.executeBatch();
				return total;
			}
		});
		return 0;
	}

	@Override
	public int deleteWithCompanyId(Map<String, Object> map) {
		return getSqlMapClientTemplate().delete(
				namespace + ".deleteWithCompanyId", map);
	}

	@Override
	public Integer getPartUloadCountByConditions(Map<String, Object> map) {

		return (Integer) getSqlMapClientTemplate().queryForObject(
				namespace + ".getCountAllPartUpload", map);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<PartUpload> getPartUploadListByConditions(
			Map<String, Object> map) {

		return getSqlMapClientTemplate().queryForList(
				namespace + ".getAllPartUpload", map);
	}

}
